/*************************************************************************
    > File Name: 1.unix_tcp_server.c
    > Author: Ykk
    > Mail: 3393579535@qq.com 
    > Created Time: 2023年05月31日 星期三 20时43分27秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<stddef.h>
#include<sys/un.h>

int main(int argc,char *argv[])
{
	unlink("ock.s");
	//创建unix流式套接字
	int lfd = socket(AF_UNIX,SOCK_STREAM,0);
	//绑定
	struct sockaddr_un myaddr;
	myaddr.sun_family = AF_UNIX;
	strcpy(myaddr.sun_path,"ock.s");
	int len1 = offsetof(struct sockaddr_un,sun_path) + strlen(myaddr.sun_path);
	bind(lfd,(struct sockaddr *)&myaddr,len1);
	//监听
	listen(lfd,128);
	//提取
	struct sockaddr_un cliaddr;
	socklen_t len2 = sizeof(cliaddr);
    int	cfd = accept(lfd,(struct sockaddr *)&cliaddr,&len2);
	printf("new client file = %s\n",cliaddr.sun_path);
	//读写
	char buf[1500];
	while(1)
	{
		int n = recv(cfd,buf,sizeof(buf),0);
		if(n <= 0)
		{
			printf("err or client close\n");
			break;
		}
		else
		{
			printf("client:%s ==>%s\n",cliaddr.sun_path,buf);
			send(cfd,buf,n,0);
		}
	}
	//关闭
	close(lfd);
	close(cfd);
	return 0;
}
